package com.cqvie.service;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cqvie.dao.CommonDao;
import com.cqvie.model.*;

@Transactional
@Service("accountService")
public class AccountService {

    @Resource
    private CommonDao commonDao;
	
    /**** 
     * 通过用户名获取用户对象 
     *  
     * @param username 
     * @return 
     */  
    public User getUserByUserName(String username) {  
        User user = (User) commonDao.findObjectByHQL("FROM User WHERE username = ?", new Object[] { username });  
        return user;  
    }  
  
    /*** 
     * 通过用户名获取权限资源 
     *  
     * @param username 
     * @return 
     */  
    public Set<String> getPermissionsByUserName(String username) {  
        User user = getUserByUserName(username);  
        if (user == null) {  
            return null;  
        }  
        Set<String> set = new HashSet<String>();  
        // System.out.println(user.getUserRoles().get(0).get);  
        for (UserRole userRole : user.getUserRoles()) {  
            Role role = userRole.getRole();  
            List<Permission> permissions = commonDao.findAllByHQL("FROM Permission WHERE roleId = ?", new Object[] { role.getId() });  
            for (Permission p : permissions) {
                set.add(p.getMethod());  
            }  
        }  
        return set;  
    }  

    /*** 
     * 通过用户名获取角色 
     *  
     * @param username 
     * @return 
     */ 
    public Set<String> getRolesByUserName(String username) {  
        User user = getUserByUserName(username);  
        if (user == null) { 
            return null;  
        }
        Set<String> set = new HashSet<String>();  
        // System.out.println(user.getUserRoles().get(0).get);  
        for (UserRole userRole : user.getUserRoles()) {  
            Role role = userRole.getRole();
            set.add(role.getName());
        }  
        return set;  
    }  

    public boolean accountAccess(String url,HttpSession session){
    	String role=(String) (session.getAttribute("jurisdiction")==null?"":session.getAttribute("jurisdiction"));
    	String username=(String) (session.getAttribute("username")==null?"":session.getAttribute("username"));
    	if (role.equals("")||username.equals("")) {
			return false;
		}
    	Set<String> set=getRolesByUserName(username);
    	for (String string : set) {		
    		if (string.equals(role)) {
				Set<String> set2=getPermissionsByUserName(username);    			
				for (String string2 : set2) {
					if (url.equals(string2)) {
						return true;
					}
				}
			}
    	}
    	return false;
    }
    
    
    public boolean addRole(Role role){
    	return commonDao.addObject(role);
    }
    
    
}  